package com.manlitech.cloudboot.oauth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.manlitech.cloudboot.oauth.pojo.UserPojo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * security 数据库账号密码查询
 * @author shensg
 * @date 2021/7/8 8:32
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws
            UsernameNotFoundException {
        //        查询数据库，角色权限，自己虚拟数据，就不在这加了
        String sql = "select  " +
                "su.id, " +
                "su.username, " +
                "su.`password`, " +
                "GROUP_CONCAT(sr.name) as name, " +
                "GROUP_CONCAT(sp.name) as rolePeisList " +
                "from  " +
                "sys_user su left join sys_role_user sru on su.id = sru.sys_user_id " +
                "left join sys_role sr on sru.sys_role_id = sr.id " +
                "left join sys_permission_role spr on spr.role_id = sr.id " +
                "left join sys_permission sp on sp.id = spr.permission_id " +
                "where username = '" + username +"' "+
                "group by id";
        UserPojo userPojo = userService.getBaseMapper().getUserPojoByUsername(sql);
        if (userPojo == null) {
            log.warn("登录用户：" + username + "不存在");
            throw new UsernameNotFoundException("登录用户：" + username + "不存在");
        }
        String rolePeisList = userPojo.getRolePeisList();//角色权限列表
        System.out.println("rolePeisList==="+rolePeisList);
        //将数据库的roles解析为UserDetails的权限集
        //AuthorityUtils.commaSeparatedStringToAuthorityList将逗号分隔的字符集转成权限对象列表
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(rolePeisList);
        return new User(userPojo.getUsername(), userPojo.getPassword(), auths);
    }
}
